package com.sgb.zhaocai.view.fragment;

import android.os.Bundle;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.databinding.DataBindingUtil;
import androidx.lifecycle.ViewModelProvider;
import androidx.recyclerview.widget.LinearLayoutManager;
import com.sgb.link.entity.PickInvitedApply;
import com.sgb.zhaocai.R;
import com.sgb.zhaocai.databinding.PickMarketCompanyFragmentBinding;
import com.sgb.zhaocai.entity.MarketCompanyEntitly;
import com.sgb.zhaocai.view.activity.PickInvitedApplyDetailsActivity;
import com.sgb.zhaocai.view.adapter.MarketCompanyAdapter;
import com.sgb.zhaocai.viewmodel.PickMarketCompanyModel;
import com.swgk.core.base.AppLazyFragment;
import com.swgk.core.view.areapopup.AddressEntity;
import com.swgk.core.view.areapopup.GoodsSourceLocationEntity;
import com.swgk.core.view.areapopup.ThreeLevelAreaWindow;
import com.swgk.core.view.selection.CommonPopEntity;
import com.swgk.core.view.selection.MemberStatusView;
import com.swgk.core.xrecyclerview.XRecyclerView;

import java.util.ArrayList;
import java.util.List;

/**
 * 市场客户-个人
 */
public class PickMarketCompanyFragment  extends AppLazyFragment implements MemberStatusView.OnChooseListener{

    private PickMarketCompanyFragmentBinding mBinding;
    private PickMarketCompanyModel mModel;

    private static String DATA = "data";
    private PickInvitedApply bean;
    private boolean isLoadMore = false;
    private int num = 0;
    private MarketCompanyAdapter marketcompanyadapter;
    private String searchnames = "";
    private static String FROMWHERE = "fromWhere";
    private String fromWhere;
    private boolean isSelectAll = false;
    //地区筛选项实现
    private ThreeLevelAreaWindow mAddressPop;
    private List<AddressEntity<List<AddressEntity<List<AddressEntity>>>>> scrData;
    private String province = "";
    private String city = "";
    private String companynature = "";
    private String rangeband = "";
    private String time = "";
    private boolean isTextview = false;

    public static PickMarketCompanyFragment newInstance(PickInvitedApply pickinvitedapply, String fromWhere) {
        PickMarketCompanyFragment fragment = new PickMarketCompanyFragment();
        Bundle bundle = new Bundle();
        bundle.putSerializable(DATA,pickinvitedapply);
        bundle.putString(FROMWHERE, fromWhere);
        fragment.setArguments(bundle);
        return fragment;
    }
    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        mBinding = DataBindingUtil.inflate(inflater, R.layout.pick_market_company_fragment, container, false);
        mModel = new ViewModelProvider(this).get(PickMarketCompanyModel.class);
        mModel.setActivity(PickMarketCompanyFragment.this);
        bean = (PickInvitedApply) getArguments().get(DATA);
        fromWhere =(String) getArguments().get(FROMWHERE);
        return mBinding.getRoot();
    }
    @Override
    protected void onLazyLoad() {

    }

    private void initData(boolean isLoadMore) {
        mModel.getBiddingCompanyList(isLoadMore,searchnames,fromWhere,bean.getId(),province,city,companynature,rangeband);
    }

    @Override
    protected void initView() {
        super.initView();
        if (marketcompanyadapter == null) {
            marketcompanyadapter = new MarketCompanyAdapter(getActivity(), null);
        }
        LinearLayoutManager layoutManager = new LinearLayoutManager(getActivity());
        mBinding.recyclerView.setLayoutManager(layoutManager);
        mBinding.recyclerView.setHasFixedSize(true);
        //解决数据加载完成后, 没有停留在顶部的问题
        mBinding.recyclerView.setFocusable(false);
        mBinding.recyclerView.setAdapter(marketcompanyadapter);
        mBinding.recyclerView.setLoadingMoreEnabled(true);
        mBinding.recyclerView.setLoadingListener(new XRecyclerView.LoadingListener() {
            @Override
            public void onRefresh() {
                isLoadMore= false;
                initData(false);
            }

            @Override
            public void onLoadMore() {
                isLoadMore = true;
                //上拉加载更多
                initData(isLoadMore);
            }
        });
        marketcompanyadapter.onIChildClick(new MarketCompanyAdapter.IChildClick() {
            @Override
            public void onClick(MarketCompanyEntitly membercompanyentitly) {
                membercompanyentitly.setCheck(!membercompanyentitly.isCheck());
                marketcompanyadapter.notifyDataSetChanged();
                invitedSureData();
            }
        });
        //全选按钮
        mBinding.llCheckAll.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (isSelectAll){
                    isSelectAll = false;
                    mBinding.checkImageview.setImageResource(R.drawable.icon_ring );
                    mBinding.invitedSure.setText("确认邀请");
                    mBinding.invitedSure.setBackground(getActivity().getResources().getDrawable(R.drawable.bg_tint_orange_5));
                    isTextview = false;
                }else {
                    isSelectAll = true;
                    mBinding.checkImageview.setImageResource(R.drawable.icon_select_item );
                    mBinding.invitedSure.setText("确认邀请("+marketcompanyadapter.getDatas().size()+")");
                    mBinding.invitedSure.setBackground(getActivity().getResources().getDrawable(R.drawable.bg_orange_5));
                    isTextview = true;
                }

                for (MarketCompanyEntitly data : marketcompanyadapter.getDatas()) {
                    data.setCheck(isSelectAll);
                }
                marketcompanyadapter.notifyDataSetChanged();
            }
        });
        //确认邀请实现
        mBinding.invitedSure.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (isTextview){
                    invitedSureDataList();
                }
            }
        });
        //置顶
        mBinding.imgBackTop.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mBinding.imgBackTop.setVisibility(View.GONE);
                mBinding.recyclerView.getLayoutManager().scrollToPosition(0);
            }
        });
        viewData();
    }

    private void viewData() {
        //初始化popview
        initializePopView();
    }

    private void initializePopView() {
        //经营地址
        initAddressPopup();
        //企业性质
        mBinding.companyNature.initPopup(mBinding.grayLayout, mBinding.popLine, this);
        //距离范围
        mBinding.rangeBand.initPopup(mBinding.grayLayout, mBinding.popLine, this);
        mModel.getRangeBandList();
        mModel.getCompanyNatureList();
    }

    //地区
    private void initAddressPopup() {
        mBinding.district.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (scrData == null || scrData.size() == 0) {
                   if (bean.getBiddingRegion()!=null&&bean.getBiddingRegion().size()>0){
                        mModel.getBiddingRegionAddressModel(bean.getId(),fromWhere);
                    }else {
                        mModel.getAddressModel();
                    }
                    return;
                }
                mBinding.popLine.setVisibility(View.VISIBLE);
                if (!TextUtils.isEmpty(province) || !TextUtils.isEmpty(city)) {
                    mBinding.district.updateChooseTextStatus(-2, null);
                } else {
                    mBinding.district.updateChooseTextStatus(-1, mBinding.district.getKeyName());
                }
                mAddressPop.showPopwindow0(mBinding.popLine);
            }
        });
        mAddressPop = new ThreeLevelAreaWindow(getActivity());
        mAddressPop.setBgView(mBinding.grayLayout);
        mAddressPop.setMemberHeight();
        mAddressPop.setCitySingle();
        mAddressPop.setProvinceSingle();
        mAddressPop.setShowSimpleName(true);
        mAddressPop.setOnlyShowProAndCity(true);
        mAddressPop.setAllSingleSelect(true);
        mAddressPop.setThreeListIsGone(true);
        mAddressPop.setOnResultClick(new ThreeLevelAreaWindow.OnResultClickProxy() {
            @Override
            protected void result(GoodsSourceLocationEntity entity) {
                province = "";
                city = "";
                mBinding.district.updateChooseTextStatus(0, mBinding.district.getKeyName());
                if (!TextUtils.isEmpty(entity.getProvinceNo())) {
                    province = entity.getProvinceNo();
                    mBinding.district.updateChooseTextStatus(1, entity.getProvinceName());
                    if (!TextUtils.isEmpty(entity.getCityNo())) {
                        city = entity.getCityNo();
                        mBinding.district.updateChooseTextStatus(1, entity.getCityName());
                    }
                }
                //刷新数据
                initData(false);
            }
        });
        mAddressPop.setOnDismissListener(() -> {
            if (!TextUtils.isEmpty(province) || !TextUtils.isEmpty(city)) {
                mBinding.district.updateChooseTextStatus(1, null);
            } else {
                mBinding.district.updateChooseTextStatus(0, mBinding.district.getKeyName());
            }
        });
    }

    //pop初始化数据
    @Override
    public void onLoadChooseData(String mKeyName) {
        switch (mKeyName) {
            case "企业性质":
                mModel.getCompanyNatureList();
                break;
            case "距离范围":
                mModel.getRangeBandList();
                break;
        }
    }

    //pop点击事件
    @Override
    public void onChooseResult(String mKeyName, CommonPopEntity entity, Object... objects) {
        int position = (int) objects[0];
        String no = position == 0 ? "" : entity.getNo();
        String id = position == 0 ? "" : entity.getId();
        String name = position == 0 ? "" : entity.getTypeName();
        switch (mKeyName) {
            case "企业性质":
                if (!TextUtils.equals(name, companynature)) {
                    companynature = name;
                }
                break;
            case "距离范围":
                if (!TextUtils.equals(no, rangeband)) {
                    rangeband = no;
                }
                break;
        }
        //刷新数据
        initData(false);
    }


    //弹窗信息
    public void setChooseItemData(int type, List<CommonPopEntity> data) {
        if (data == null || data.size() == 0) return;
        switch (type) {
            case 1://企业性质
                mBinding.companyNature.setData(data, companynature);
                break;
            case 2://距离范围
                mBinding.rangeBand.setData(data, rangeband);
                break;
        }
    }

    /**
     * 地址信息
     * @param data
     */
    public void setAddressList(List<AddressEntity<List<AddressEntity<List<AddressEntity>>>>> data) {
        if (data != null && data.size() > 0) {
            scrData = data;
            mAddressPop.setData(data, true);
            mBinding.popLine.setVisibility(View.VISIBLE);
            if (!TextUtils.isEmpty(province) || !TextUtils.isEmpty(city)) {
                mBinding.district.updateChooseTextStatus(-2, null);
            } else {
                mBinding.district.updateChooseTextStatus(-1, mBinding.district.getKeyName());
            }
            mAddressPop.showPopwindow0(mBinding.popLine);
        }
    }

    public void setBiddingCompanyList(List<MarketCompanyEntitly> data, int listSize) {
        RecyclerRefreshing();
        if (isLoadMore) {
            if (data != null && data.size() > 0) {
                marketcompanyadapter.addDatas(data);
            }
            if (listSize>=marketcompanyadapter.getDatas().size()){
                mBinding.recyclerView.setNoMore(false);
            }else {
                mBinding.recyclerView.setNoMore(true);
            }
            mBinding.imgBackTop.setVisibility(View.VISIBLE);

        } else {
            if (data != null && data.size() > 0) {
                mBinding.emptyView.setVisibility(View.GONE);
                mBinding.recyclerView.setVisibility(View.VISIBLE);
                mBinding.llBottom.setVisibility(View.VISIBLE);
                marketcompanyadapter.clearDatas();
                marketcompanyadapter.setDatas(data);
                mBinding.recyclerView.scrollToPosition(0);
                if (listSize>=marketcompanyadapter.getDatas().size()){
                    mBinding.recyclerView.setNoMore(false);
                }else {
                    mBinding.recyclerView.setNoMore(true);
                }
                mBinding.imgBackTop.setVisibility(View.GONE);
            } else {
                mBinding.imgBackTop.setVisibility(View.GONE);
                marketcompanyadapter.clearDatas();
                mBinding.emptyView.setVisibility(View.VISIBLE);
                mBinding.recyclerView.setVisibility(View.GONE);
                mBinding.llBottom.setVisibility(View.GONE);
            }
        }
        invitedSureData();
    }

    private void invitedSureData() {
        num=0;
        if (marketcompanyadapter.getDatas()!=null&&marketcompanyadapter.getDatas().size()>0){
            for (MarketCompanyEntitly datas : marketcompanyadapter.getDatas()) {
                if (!datas.isCheck()){
                    //全选按钮设置成不全选
                    if (isSelectAll){
                        isSelectAll = false;
                    }
                    mBinding.checkImageview.setImageResource(R.drawable.icon_ring );
                }else {
                    num++;
                }
            }
            if (num == 0){
                mBinding.invitedSure.setText("确认邀请");
                mBinding.invitedSure.setBackground(getActivity().getResources().getDrawable(R.drawable.bg_tint_orange_5));
                isTextview = false;
            }else {
                mBinding.invitedSure.setText("确认邀请("+num+")");
                mBinding.invitedSure.setBackground(getActivity().getResources().getDrawable(R.drawable.bg_orange_5));
                isTextview = true;
            }
        }
    }



    private void RecyclerRefreshing() {
        mBinding.recyclerView.refreshComplete();
        mBinding.recyclerView.loadMoreComplete();
    }

    public void initSearch(String SearchName) {
        this.searchnames = SearchName;
        initData(false);
    }

    public void setCompanyNatureList(List<CommonPopEntity> datas) {
        setChooseItemData(1, datas);
    }

    public void setRangeBandList(List<CommonPopEntity> datas) {
        setChooseItemData(2, datas);
    }
    //提交数据
    private void invitedSureDataList() {
        List<String> companyList = new ArrayList<>();
        List<String> companynameList = new ArrayList<>();
        if (TextUtils.equals(fromWhere, "1")) {
            time =   bean.getApplyEndTime();
        } else {
            time = "";
        }
        for (MarketCompanyEntitly data : marketcompanyadapter.getDatas()) {
            if (data.isCheck()){
                companyList.add(data.getCompanyNo());
                companynameList.add(data.getCompanyName());
            }
        }
        if (companyList.size()>0){
            PickInvitedApplyDetailsActivity.start(getActivity(), fromWhere, bean.getName(), time, 0, companyList,bean.getId(),new ArrayList<>(),companynameList,new ArrayList<>(),0,"");
        }else {
           // MToast.showToast(getActivity(),"请选择市场客户企业数据");
        }
    }

    //重置筛选项
    public void RemoveScreenData() {
        initializePopView();
        //地址清除
        province = "";
        city = "";
        rangeband = "";
        companynature = "";
        if (scrData != null && scrData.size() > 0) {
            mAddressPop.setData(scrData, true);
        }
        mBinding.district.refreshChoose("", "", 0);
        mAddressPop.setDefPosition(0, 0);
        mBinding.companyNature.updateChooseTextStatus(0, mBinding.companyNature.getKeyName());
        mBinding.rangeBand.updateChooseTextStatus(0, mBinding.rangeBand.getKeyName());
       initData(false);
    }
}
